import { Component, OnInit, OnDestroy, Input, Output, EventEmitter, forwardRef } from '@angular/core';
import { NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
  selector: 'app-tiny-editor',
  templateUrl: './tiny-editor.component.html',
  styleUrls: ['./tiny-editor.component.less'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => TinyEditorComponent),
      multi: true
    }
  ]
})
export class TinyEditorComponent implements OnInit {
  [x: string]: any;
  /**
   * 系统中一共有以下地方使用到了富文本，
   * - 工单模板
   * - 创建/处理工单
   * - 工单通知
   * - faq 配置页面
   * - faq 创建/编辑页面
   * - 内容模板配置
   * - itsm 通知配置
   * 在系统管理的页面富文本，不能创建图片，
   * 在创建编辑的地方可以上传图片
   * 在通知管理中用户可以输入 $ 开头的文件，将工单、itsm的字段联想出来，方便用户选择
   */

  // @Output() richTextContent = new EventEmitter<string>();
  // @Output() richPureText = new EventEmitter<string>();
  @Input() editorType!: string;
  @Input() elementId!: String;
  private _value: any;
  url: string = window.location.protocol + window.location.host 
  editConfig: any;
  constructor() {}
  set value(value: any) {
    this._value = value;
    this.onValueChange(value);
  }

  get value(): any {
    return this._value;
  }
  ngOnInit(): void {
    this.editInit();
  }

  writeValue(value: any): void {
    if (value) {
      this._value = value;
    }
  }

  registerOnChange(fn: any): void {
    this.onValueChange = fn;
  }

  registerOnTouched(fn: any): void {}
  private onValueChange(value: any): void {}

  specialChars = [
    { text: 'exclamation mark', value: '!' },
    { text: 'at', value: '@' },
    { text: 'hash', value: '#' },
    { text: 'percent sign', value: '%' },
    { text: 'caret', value: '^' },
    { text: 'ampersand', value: '&' },
    { text: 'asterisk', value: '*' }
  ];

  editInit(): void {
    //const editorType = this.editorType;
    console.log('this.elementId ', this.elementId, this.editorType);
    this.editConfig = {
      selector: `#${this.elementId}`,
      base_url: '/tinymce',
      promotion: false, // 右上角 upgrade 隐藏
      resize: true,
      plugins: 'wordcount',
      // 禁用粘贴图片
      paste_preprocess: (plugin: any, args: { content: string }) => {
        console.log('this.editorType ', this.editorType);
        if (this.editorType === 'notification1') {
          // replace copied text with empty string
          args.content = args.content.replace(/<img.*?(?:>|\/>)/gi, '');
        }
      },
      language_url: '/assets/tiny/langs/zh-Hans.js',
      language: 'zh-Hans',
      // language_url: publicPath + 'resource/tinymce/langs/' + langName.value + '.js',
      // language: langName.value,
      theme: 'silver',
      // skin: skinName.value,
      // skin_url: publicPath + 'resource/tinymce/skins/ui/' + skinName.value,
      branding: false,
      default_link_target: '_blank',
      link_title: false,
      auto_focus: true,
      extraPlugins: 'uploadimage',
      imageUploadUrl: '/user',
      toolbar:
        'undo redo | formatselect | fontselect fontsizeselect lineheight | bold italic underline strikethrough forecolor backcolor | \
		      alignleft aligncenter alignright alignjustify removeformat | preview template codesample remove selectall link image fullscreen wordcount',
      setup: (editor: any) => {
        editor.on('keyup', () => {
          // const content = editor.getContent();
          // this.onEditorKeyup.emit(content);
        });
        editor.on('input', () => {
          this.value = editor.getContent();
        });
        const onAction = (autocompleteApi: any, rng: any, value: string): void => {
          console.log('value ', value);
          editor.selection.setRng(rng);
          editor.insertContent(value);
          autocompleteApi.hide();
        };

        const getMatchedChars = (pattern: string): any => {
          return this.specialChars.filter(char => char.text.indexOf(pattern) !== -1);
        };
        /**
         * An autocompleter that allows you to insert special characters.
         * Items are built using the CardMenuItem.
         */
        editor.ui.registry.addAutocompleter('specialchars_cardmenuitems', {
          trigger: '$',
          minChars: 1,
          columns: '1',
          onAction: onAction,
          highlightOn: ['char_name'],
          fetch: (pattern: string) => {
            return new Promise(resolve => {
              const results = getMatchedChars(pattern).map((char: { value: any; text: any }) => ({
                type: 'cardmenuitem',
                direction: 'vertical',
                value: `<DMC_TICKET_${char.value}>`,
                label: `${char.text}`,
                items: [
                  {
                    type: 'cardcontainer',
                    direction: 'vertical',
                    align: 'left',
                    valign: 'middle',
                    items: [
                      {
                        type: 'cardtext',
                        text: char.text,
                        name: 'char_name'
                      },
                      {
                        type: 'cardtext',
                        text: char.value,
                        name: 'char_name'
                      }
                    ]
                  }
                ]
              }));
              resolve(results);
            });
          }
        });
      },
      paste_data_images: true,
      images_upload_handler: (blobInfo: any, succFun: any, failFun: any) => {
        let xhr: XMLHttpRequest;
        let formData;
        const file = blobInfo.blob();
        xhr = new XMLHttpRequest();
        xhr.withCredentials = false;
        xhr.open(
          'POST',
          // 上传图片服务器地址
          'http://101.43.17.41:8083/live/ticket/upload'
        );
        console.log('images_upload_handler');
        if (xhr.readyState === 1) {
          xhr.setRequestHeader('Accept', 'application/json');
          xhr.setRequestHeader('Content-Type', 'application/json, text/plain, */*');
          xhr.setRequestHeader('Authorization', 'test');
        }

        //xhr.setRequestHeader('token', 'sdsds');
        xhr.onload = () => {
          let json;
          console.log('xhr.status ', xhr.status);
          if (xhr.status !== 200) {
            failFun(`HTTP Error: ${xhr.status}`);
            return;
          }
          json = JSON.parse(xhr.responseText);
          // 在 tinymce 中上传的图片为在线图片，开头以  inline 开头 /inline/:attachemntid/filename
          succFun(`https://file.test.biz:4445/${json.listData[0].cDirRelativePath}/${json.listData[0].cUpDocumentName}`);
        };
        formData = new FormData();
        formData.append('file', file, file.name);
        // 将图片显示到富文本编辑器中
        xhr.send(formData);
      },
      urlconverter_callback: (url: string, node: any, on_save: any, name: string) => {
        const assignUrl = ['file:///C:', 'https://lms0-1251107588'];
        let isInnerUrl = false; //默认不是内部链接
        try {
          assignUrl.forEach(item => {
            if (url.indexOf(item) > -1) {
              isInnerUrl = true;
              throw new Error('EndIterate');
            }
          });
        } catch (e) {
          // if (e.message != 'EndIterate') throw e;
        }
        if (!isInnerUrl) {
          // replaceUrl(url).then(result => {
          //   if (result.data.code == 0) {
          //     this.newImgUrl.push(result.data.data);
          //   }
          // });
        }
        return url;
      }
    };
  }
}
